package com.shopping.product.web;

import com.shopping.product.entity.CategoryEntity;
import com.shopping.product.service.CategoryService;
import com.shopping.product.vo.Catalog2Vo;
import org.redisson.api.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Europa
 * @create 2020-06-06 18:16
 */
@Controller
public class IndexController {

    @Resource
    CategoryService categoryService;

    @Resource
    RedissonClient redisson;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/", "/index.html"})
    public String index(Model model) {
        List<CategoryEntity> list = categoryService.getLevel1Category();
        //视图解析器拼接字符串
        //classpath:/templates/返回值 + .html
        model.addAttribute("categories", list);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        return categoryService.getCatalogJson();
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //名字相同就为同一把锁
        RLock rLock = redisson.getLock("my-lock");
        //加锁10秒,10秒后自动解锁,加锁时间要超过业务时间
        //若不写时间,则默使用30s,每10s续一次,直到30s结束
        rLock.lock(10, TimeUnit.SECONDS);
        try {
            System.out.println("加锁成功.... " + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁
            System.out.println("释放锁.... " + Thread.currentThread().getId());
            //由于上面自动解锁,会导致这里解锁会找不到锁,会抛出IllegalMonitorStateException
            //rLock.unlock();
        }
        return "hello";
    }

    @ResponseBody
    @GetMapping("/write")
    public String write() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        rLock.lock();
        try {
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("write", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read() {
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            s = stringRedisTemplate.opsForValue().get("write");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return s;
    }

    /**
     * 用Semaphore模拟占用停车位
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() {
        RSemaphore park = redisson.getSemaphore("park");
        try {
            //占位,信号量-1,当信号量为0时,则无法占位进入阻塞状态
            park.acquire();
            //尝试获取信号量park.tryAcquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "park";
    }

    /**
     * 用Semaphore模拟离开停车位
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/go")
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        //当触发代码时,信号量+1
        park.release();
        return "go";
    }

    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        try {
            door.trySetCount(5);
            door.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "锁门";
    }

    @ResponseBody
    @GetMapping("/unlockDoor/{id}")
    public String unlockDoor(@PathVariable("id") String id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();
        return id + " 离开";
    }

}
